#
# CVSPrefsDialog.py
#
# Dialog for setting Preferences for the SNiFF+ CVS Adapter
#
# Author: Martin Oberhuber
# Copyright (c) 1998, 1999 TakeFive Software, Salzburg
#
# Revisions:
#

# some system modules
import sys
import os
import string

# debug variable
import CVSPrefs

# some SNiFF+ modules
from etgui import *
from PageLayout import *
import CmdNo
import ListEditor

# the dialog tab sheet classes

#--------------------------------------------------------------------------------
# the Repository List dictionary editor
#--------------------------------------------------------------------------------
class RepositoryListEditor(ListEditor.AbstrListEditor):
		"""A class that does simple dictionary editing"""
		#
		# class private variables
		__dict = None	# the dictionary Store
		__model = None  # the used Model (Data Store)
		__path = None   # the path to the data inside the model
		#
		# Constructor
		def __init__(self, aModel, aPath):
				# intialize variables
				self.__dict = None
				self.__model = aModel
				self.__path = aPath
				# call baseclass constructor
				ListEditor.AbstrListEditor.__init__(self)
		#
		# Model manipulating functions
		def DoSetItems(self, dict):
				if CVSPrefs.TEST: print "(CVS Repository List Editor)@B@g>>>@x DoSetItems@B"
				# save the dictionary
				self.__dict = dict
				# build the items list
				self.items = []		# clear the list ;)
				for aKey in self.__dict.keys():
						self.items.append(aKey)
						# self.items.append("%s" % aKey + " --> %s" % self.__dict[aKey])
				# sort the items list
				self.items.sort()
				if CVSPrefs.TEST:
						print "(CVS Repository List Editor)\tresulted dictionary: @B@r",
						print self.__dict,
						print "@x@B"
						print "(CVS Repository List Editor)\tresulted items list: @B@r",
						print self.items,
						print "@x@B"
						print "(CVS Repository List Editor)@B@r<<<@x DoSetItems@B"
				return self.items

		def DoMakeItem(self,key):
				if CVSPrefs.TEST:
						print "(CVS Repository List Editor)@B@g>>>@x DoMakeItem@B"
				textStyle = eFacePlain | eFaceBold
				aTextItem = None
				aTextItem = TextItem(str(key),
															font=Font(
																gSysFont.Fid(),
																gSysFont.Size(),
																textStyle
															)
														)

				if CVSPrefs.TEST: print "(CVS Repository List Editor)@B@r<<<@x DoMakeItem@B"
				return aTextItem

		def insertSorted(self, key, value=""):
				"""insert into sorted List."""
				marker="insertSorted: "
				print marker,key,",",value
				k=-1
				for k in range(len(self.items)):
						if self.items[k] > key:
								break
				else:
						k=k+1
				print marker,"k=",k
				if k>0 and self.items[k-1]==key:
						if CVSPrefs.TEST:
								print "(CVS Repository List Editor)\tFound double keys: %s; no insert action performed !" % key
								return -1
				else:
						self.items.insert(k, key)
						self.__dict[key] = value
						self.updateModel()
				return k
		def DoInsert(self, i, key):
				"""New button pressed or called after Rename"""
				if CVSPrefs.TEST: print "(CVS Repository List Editor)@B@g>>>@x DoInsert (index = %d)@B" % i
				newpos=self.insertSorted(key)
				if CVSPrefs.TEST:
						print "(CVS Repository List Editor)\tresulted dictionary: @B@r",
						print self.__dict,
						print "@x@B"
						print "(CVS Repository List Editor)\tresulted items list: @B@r",
						print self.items,
						print "@x@B"
						print "(CVS Repository List Editor)@B@r<<<@x DoInsert (k = %d)@B" % newpos
				return newpos
		def DoDelete(self,i):
				"""Delete Button pressed or called during Rename"""
				if CVSPrefs.TEST: print "(CVS Repository List Editor)@B@g>>>@x DoDelete (index = %d)@B" % i
				key=self.items[i]
				del self.__dict[key]
				del self.items[i]
				self.updateModel()
				if CVSPrefs.TEST:
						print "(CVS Repository List Editor)\tresulted dictionary: @B@r",
						print self.__dict,
						print "@x@B"
						print "(CVS Repository List Editor)\tresulted items list: @B@r",
						print self.items,
						print "@x@B"
						print "(CVS Repository List Editor)@B@r<<<@x DoDelete@B"
				return 1

		# Button Definitions and Customizations.
		DoSwap=None
		label_rename="Edit..."

		# Override Constructor list to get the rename button on top and add Test Button
		def DoGetButtonConstructors(self):
				return [
						self.MakeRenameButton,
						self.MakeNewButton,
						self.MakeCopyButton,
						self.MakeDeleteButton,
						self.MakeTestButton
				]
		# "Edit" Button pressed with Item i selected
		def DoRename(self, i):
				print "DoRename xy"
				key = self.items[i]
				newKey = self.ShowEditDialog("Edit", key)
				if newKey:
						# OK pressed
						if newKey == key or self.__dict.has_key(newKey):
								# Do nothing if new value is same as before or already in dict
								return None
						else:
								oldValue = self.__dict[key]
								self.insertSorted(key, oldValue)
								# baseclass'es _rename will delete the old key
				return newKey
		# "New" Button pressed with Item i selected
		def DoNew(self, i):
				retValue = self.ShowEditDialog("New", "")
				if not retValue:
						return None
				return retValue
		# "Copy" Button pressed with Item i selected
		def DoCopy(self, i):
				key = self.items[i]
				retValue = self.ShowEditDialog("Copy", key)
				# don't insert new value if same as before
				if not retValue or retValue == key:
						return None
				return retValue
		def MakeTestButton(self):
				return self.NewButton("Test",self.DoTest,self.CanEdit)
		# "Test" Button pressed with Item i selected
		def DoTest(self, i):
				key = self.items[i]
				try:
						value = self.__dict[key]
				except KeyError:
						value = "--nil--"
				print "Here is Key: ",key," with value: ",value

		# The Edit sub-dialog: a simple input field
		def ShowEditDialog(self, how, defaultKey):
				model = PotGuiModel()
				model.SetValue("Key", defaultKey)
				defaultWidth=min(40, max(len(defaultKey)+5, 30))
				retval=ShowSubDialog("%s %s" % (how, "CVSROOT"),
						model,
						MakeSectionLayout(
								Form(
										items=[
												"CVSROOT:", PotTextField("Key", width=defaultWidth),
										]
								)
						)
				)
				if retval:
						newKey = model.GetValue("Key")
						return newKey
				else:
						return None

		# hold the GUI model up to date
		def updateModel(self):
				self.__model.SetValue(self.__path, self.__dict)

		def DoMakePreview(self,model):
				return MakePageLayout(eVObjHExpand|eVObjVCenter,
						Form(
								items=[
										"Local Proxy",PotTextField("LocalProxy"),
								]
						)
				)

#--------------------------------------------------------------------------------
#
#--------------------------------------------------------------------------------
# some functions to create the dialog
def MakeRepositoryListSheet(model, path):
		# create the editor
		editor = RepositoryListEditor(model, path)
		# gather the items
		editor.SetItems(model.GetValue(path))
		return MakeSectionLayout(
				MakeListEditorLayout(editor)
		)	# MakeSectionLayout

class ToggleButtonEnabler(FieldEnabler):
		def IsEnabled(self,value):
				return value=="Enable"

def MakeGeneralPrefsSheet(model):
		# create the page fields and set the attributes
		cbVCSDebug = PotGuiToggleButton("VCSDebug", "Show basic adapter debug information")
		cbCVSDebug = PotGuiToggleButton("CVSDebug", "Show CVS specific detailed debug information")
		return MakePageLayout(eVObjHExpand | eVObjVExpand,
				MakeBorderedSectionLayout("Adapter Debug settings",
						Form (
								items=[
										VBox(
												items=[
														cbVCSDebug,
														cbCVSDebug,
												] # items
										) # VBox
								] # items
						) # Form
				) # MakeBorderedSectionLayout
		) # MakePageLayout

def MakeConfigFilePrefsSheet(model):
		# create the page field and set the attributes
		aMasterConfigFileSelector = PotGuiFileSelector("CVS Master Config File", gTextFieldLen, "CVS Config File")
		aProjectConfigFileSelector = PotGuiFileSelector("CVS Project Config File", gTextFieldLen, "CVS Config File")
		# create tab page layout
		return MakeSectionLayout(
				MakePageLayout(eVObjHExpand|eVObjVExpand,
						MakeBorderedSectionLayout("CVS related Config Files",
								Form(
										items=[
													"Master Config File", aMasterConfigFileSelector,
													"Project Config File", aProjectConfigFileSelector
										]	# items
								)	# Form
						),	# MakeBorderedSectionLayout
						MakeBorderedSectionLayout("SNiFF+ related Config Files",
								Form(
										items=[
												VBox(
														items=[
																	"SNiFF+ Master Config File:",
																TextItem("%s" % model.GetValue("SNiFF+ Master Config File"))
														] # items
												) # VBox
										]	# items
								)	# Form
						)	# MakeBorderedSectionLayout
				)	# MakePageLayout
		)	# MakeSectionLayout

def ShowPrefsDialog(aInputRepositoryListDict,
										sniffMasterFile,
										CVSMasterFile,
										CVSProjectFile,
										VCSDebug,
										CVSDebug
									):
		if CVSPrefs.TEST: print "(CVS Prefs Dialog)@B@g>>>@x ShowPrefsDialog@B"
		# Create a model used in the dialog to store data
		model = PotGuiModel()
		# Set the shown values
		# General View
		model.SetValue("VCSDebug", VCSDebug)
		model.SetValue("CVSDebug", CVSDebug)
		# Config File View
		model.SetValue("CVS Master Config File", CVSMasterFile)
		model.SetValue("CVS Project Config File", CVSProjectFile)
		model.SetValue("SNiFF+ Master Config File", sniffMasterFile)
		# CVSROOT Translation view
		model.SetValue("Repository List", aInputRepositoryListDict)
		aPanel = PotGuiPanel(gPoint6,eVObjVExpand|eVObjHExpand)
		aPanel.AddPage(MakeHeader("General", "General integration settings",
															MakeGeneralPrefsSheet(model)), 0, "General settings")
		aPanel.AddPage(MakeHeader("Config Files", "Used CVS config files",
															MakeConfigFilePrefsSheet(model)), 1, "Config Files")
		aPanel.AddPage(MakeHeader("Repository List", "Known CVSROOTs and Translations",
															MakeRepositoryListSheet(model, "Repository List")), 0, "Repositories")
		aPanel.Update()
		retval=ShowSubDialog("CVS Integration Preferences",
				model,
				MakePageLayout(eVObjHExpand|eVObjVExpand,
						aPanel
				) # MakePageLayout
		) # ShowSubDialog
		if not retval:
				# Cancel button pressed
				model = None
		if CVSPrefs.TEST: print "(CVS Prefs Dialog)\tShowPrefsDialog @BretValue: @b%d@x@B" % retval
		if CVSPrefs.TEST: print "(CVS Prefs Dialog)@B@r<<<@x ShowPrefsDialog@B"
		return model

def Show(aInputRepositoryListDict,
					sniffMasterFile,
					CVSMasterFile,
					CVSProjectFile,
					VCSDebug,
					CVSDebug
				):
		if CVSPrefs.TEST: print "(CVS Prefs Dialog)@B@g>>>@x Show@B"
		model = ShowPrefsDialog(
						aInputRepositoryListDict,
						sniffMasterFile,
						CVSMasterFile,
						CVSProjectFile,
						VCSDebug,
						CVSDebug
				)
		if CVSPrefs.TEST: print "(CVS Prefs Dialog)@B@r<<<@x Show@B"
		return model

if __name__ == '__main__':
		model = Show({":server:mober@apollo:/Users/mober/.cvsroot" : "/Users/mober/.cvsroot"},
					"sniffMasterFile",
					"CVSMasterFile",
					"CVSProjectFile",
					1,
					2
				)

